import React, { useRef, useEffect, useState, useCallback, useMemo } from 'react';
import { View, ScrollView, Text } from '@tarojs/components';
import { VirtualScrollCore, VirtualScrollProps, VirtualScrollItem } from '@repo/virtual-scroll';

// 调试版本的虚拟滚动组件
export function VirtualScrollDebug<T = any>(props: VirtualScrollProps<T>) {
  const {
    items,
    height,
    estimatedItemHeight,
    overscan = 5,
    waterfall = false,
    waterfallColumns = 2,
    waterfallGap = 10,
    getItemId,
    renderItem,
    calculateHeight,
    onScroll,
    onVisibleItemsChange,
    className,
    style,
  } = props;

  const containerRef = useRef<any>(null);
  const [scrollTop, setScrollTop] = useState(0);
  const [visibleItems, setVisibleItems] = useState<VirtualScrollItem<T>[]>([]);
  const [containerWidth, setContainerWidth] = useState(0);
  const [debugInfo, setDebugInfo] = useState({
    totalItems: 0,
    visibleCount: 0,
    scrollTop: 0,
    totalHeight: 0,
  });

  // 创建虚拟滚动核心实例
  const virtualScroll = useMemo(() => {
    console.log('创建虚拟滚动实例:', { height, estimatedItemHeight, waterfall });
    return new VirtualScrollCore({
      height,
      estimatedItemHeight,
      overscan,
      waterfall,
      waterfallColumns,
      waterfallGap,
    });
  }, [height, estimatedItemHeight, overscan, waterfall, waterfallColumns, waterfallGap]);

  // 更新数据源
  useEffect(() => {
    console.log('更新数据源:', items.length);
    virtualScroll.updateItems(items, getItemId, calculateHeight);
    setDebugInfo(prev => ({ ...prev, totalItems: items.length }));
  }, [items, getItemId, calculateHeight, virtualScroll]);

  // 设置容器宽度（瀑布流需要）
  useEffect(() => {
    if (waterfall) {
      const defaultWidth = 375;
      setContainerWidth(defaultWidth);
      virtualScroll.setContainerWidth(defaultWidth);
      console.log('设置容器宽度:', defaultWidth);
    }
  }, [waterfall, virtualScroll]);

  // 处理滚动事件
  const handleScroll = useCallback((event: any) => {
    const newScrollTop = event.detail.scrollTop || 0;
    setScrollTop(newScrollTop);
    setDebugInfo(prev => ({ ...prev, scrollTop: newScrollTop }));
    onScroll?.(newScrollTop);
  }, [onScroll]);

  // 更新可见项目
  useEffect(() => {
    const newVisibleItems = virtualScroll.getVisibleItems(scrollTop, height);
    setVisibleItems(newVisibleItems);
    setDebugInfo(prev => ({
      ...prev,
      visibleCount: newVisibleItems.length,
      totalHeight: virtualScroll.getTotalHeight()
    }));
    onVisibleItemsChange?.(newVisibleItems);
    console.log('可见项目更新:', newVisibleItems.length, '个');
  }, [scrollTop, height, virtualScroll, onVisibleItemsChange]);

  // 获取总高度
  const totalHeight = useMemo(() => {
    return virtualScroll.getTotalHeight();
  }, [virtualScroll, items]);

  // 渲染可见项目
  const renderVisibleItems = () => {
    console.log('渲染可见项目:', visibleItems.length);
    return visibleItems.map((item) => {
      const itemStyle: React.CSSProperties = {
        position: 'absolute',
        top: item.top || 0,
        left: waterfall ? (item.left || 0) : 0,
        width: waterfall ? (item.width || 'auto') : '100%',
        height: item.height || estimatedItemHeight,
      };

      return (
        <View
          key={item.id}
          style={itemStyle}
          className="virtual-scroll-item"
        >
          {renderItem(item)}
        </View>
      );
    });
  };

  const containerStyle: React.CSSProperties = {
    height,
    position: 'relative',
    ...style,
  };

  return (
    <View className="virtual-scroll-debug">
      {/* 调试信息 */}
      <View className="debug-info">
        <Text className="debug-text">总项目: {debugInfo.totalItems}</Text>
        <Text className="debug-text">可见项目: {debugInfo.visibleCount}</Text>
        <Text className="debug-text">滚动位置: {debugInfo.scrollTop}</Text>
        <Text className="debug-text">总高度: {debugInfo.totalHeight}</Text>
      </View>

      <ScrollView
        ref={containerRef}
        className={`virtual-scroll-container ${className || ''}`}
        style={containerStyle}
        scrollY
        onScroll={handleScroll}
      >
        <View
          className="virtual-scroll-content"
          style={{
            height: totalHeight,
            position: 'relative',
          }}
        >
          {renderVisibleItems()}
        </View>
      </ScrollView>
    </View>
  );
}

// 重新导出类型
export type { VirtualScrollProps, VirtualScrollItem } from '@repo/virtual-scroll';
